package com.wangs.sentinel.controlle;


import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.wangs.sentinel.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class HelloController {
    private static final String RESOURCE_NAME = "hello";
    private static final String USER_RESOURCE_NAME = "user";
    private static final String DEGRADE_RESOURCE_NAME = "degrade";

    @RequestMapping("/hello")
    public String hello() {
        /**
         * 侵入性强：用 sentinelResource 注解替代
         * 改善接口中 资源定义，被流控降级 规则后的处理规则。
         * 使用步骤：
         * 1.添加依赖 sentinel-annotation-aspectj
         * 2.配置bean SentinelResourceAspect
         * @SentinelResource(value="资源名称“,blockHandle="流控降级后的处理方法”,fallback="接口出现的异常处理")
         * 处理方法 默认被声明在同一个类中，
         */
        Entry entry = null;
        try {
            //针对资源进行限制
            entry = SphU.entry(RESOURCE_NAME);

            //被保护的业务逻辑
            String str = "hello world";
            log.info("------" + str + "------");
            return str;
        } catch (BlockException e) {
            //资源访问受阻，被限流或者降级处理
            log.info("block了");
            return "被流控了！";
        } catch (Exception ex) {
            //配置降级规则，记录业务异常
            Tracer.traceEntry(ex, entry);
        } finally {
            if (entry == null) {
                entry.exit();
            }
        }
        return null;
    }

    /**
     * 定义规则 spring的初始化方法
     */
    @PostConstruct  //<init-method>
    private static void initFlowRules() {
        //流控规则
        List<FlowRule> flowRules = new ArrayList<>();
        //流控
        FlowRule rule = new FlowRule();
        //设置受保护的资源
        rule.setResource(RESOURCE_NAME);
        //设置流控规则
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //设置受保护的资源阀值 set limit qps to 20
        rule.setCount(1);
        flowRules.add(rule);

        /**
         * 通过@SentinelResource来定义资源 并配置流控和降级
         */
        FlowRule rule1 = new FlowRule();
        rule1.setResource(USER_RESOURCE_NAME);
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setCount(1);
        flowRules.add(rule1);

        //加载配置好的规则
        FlowRuleManager.loadRules(flowRules);
    }

    @RequestMapping("/user")
    @SentinelResource(value = USER_RESOURCE_NAME, blockHandler = "blockHandlerForGetUser",
            fallback = "fallbackGetUser")
//    @SentinelResource(value="RESOURCE_NAME",blockHandlerClass=User.class)
    public User getUser(String id) {
        int a = 1 / 0;
        return new User("汪涛");
    }

    /**
     * ！：public 修饰，
     * 返回值和原方法保持一致（包含原方法的参数）；
     * 可以在参数后，加 BlockException 可以区分是什么规则的处理方法
     * 也可以放在实体类中
     *
     * @param id
     * @param e
     * @return
     */
    public User blockHandlerForGetUser(String id, BlockException e) {
        e.printStackTrace();
        return new User("流浪控制！");
    }

    public User fallbackGetUser(String id, Throwable throwable) {
        return new User("异常信息！");
    }

    @PostConstruct
    public void initDegradeRule() {
        //降级规则 异常
        List<DegradeRule> degradeRules = new ArrayList<>();
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource(DEGRADE_RESOURCE_NAME);
        //设置规则侧率 异常数
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        //出发熔断异常数 2
        degradeRule.setCount(2);
        //触发熔断最小请求数 2
        degradeRule.setMinRequestAmount(2);


        //统计时长，在多长时间段内 请求触发熔断
        degradeRule.setStatIntervalMs(60 * 1000);//时间短的话，不好测试 1分钟

        // 1分钟内，请求了两次，触发了两次异常，就会触发熔断

        //熔断持续时长，单位 秒，
        // 一旦触发了熔断，再次请求对应的接口，就会直接调用 降级方法
        // 10秒过后，--半开状态，恢复接口请求调用，如果第一次请求就异常，再次熔断，不会在根据设置的条件进行判定。
        degradeRule.setTimeWindow(10);

        degradeRules.add(degradeRule);
        DegradeRuleManager.loadRules(degradeRules);
    }

    @RequestMapping("/degradeRule")
    @SentinelResource(value = DEGRADE_RESOURCE_NAME, entryType = EntryType.IN,
            blockHandler = "blockHandlerForFb")
    public User degradeRule(String id) throws InterruptedException {

        throw new RuntimeException("运行异常！");
        //慢调用比例
//        TimeUnit.SECONDS.sleep(1);
//        return new User("正常!");
    }

    public User blockHandlerForFb(String id, BlockException e) {
        return new User("异常了！");
    }
}
